package learn.ch1.demo21;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @Description todo
 * @Author yusj
 * @Date 2021/12/13
 * @Version 1.0
 */
public class Containner {
    LinkedList list = new LinkedList();
    private Object putlock=new Object();
    private Object getlock=new Object();

    public synchronized int getCount(){
        return list.size();
    }

    public  void add(Object o){
        synchronized (putlock){
            if(list.size()<10){
                System.out.println(Thread.currentThread().getName()+" add "+o);
                list.add(o);
            }else{
                try {
                    putlock.wait();
                    getlock.notifyAll();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public  Object get(){
        synchronized (getlock){
            if(list.size()>0){
                Object o=list.removeFirst();
                System.out.println(Thread.currentThread().getName()+" get "+o);
                return o;
            }else{
                try {
                    getlock.wait();
                    putlock.notifyAll();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    public static void main(String[] args) {
        Containner  containner=new Containner();

        //2 生产者
        for(int i=0;i<2;i++){
            new Thread(()->{
                for(int j=0;j<10;j++){
                    containner.add("product-thread-p->"+j);
                }
                System.out.println("after product...");
            },"product-thread-"+i).start();
        }

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        //10 消费者
        for(int i=0;i<10;i++){
            new Thread(containner::get,"consumer-thread-"+i).start();
        }


    }


}
